//
//  UICollectionViewController.swift
//  DemoUI
//  9宫格布局
//  Created by 白瑾浩 on 2022/1/10.
//

import UIKit

class UICollectionViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
   //UICollectionViewDelegate

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .white
        
        //创建集合视图布局类
        let layout = UICollectionViewFlowLayout()
        //设置布局的竖直方向
        layout.scrollDirection = .vertical
        //设置每个数据载体的尺寸
        layout.itemSize = CGSize(width: 100, height: 100)//根据计算
        //最小行间距
        layout.minimumLineSpacing = 30
        //最小列间距
        layout.minimumInteritemSpacing = 100
        //设置头视图尺寸
        layout.headerReferenceSize = CGSize(width: self.view.frame.size.width, height: 100)
        layout.footerReferenceSize = CGSize(width: self.view.frame.size.width, height: 100)
        layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
        
        //创建集合视图
        let mUICollectionView = UICollectionView(frame: self.view.frame,collectionViewLayout: layout)
        
        //设置数据和代理源
        mUICollectionView.dataSource = self
        mUICollectionView.delegate = self
        //注册数据载体类
        mUICollectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "itemid")
        
        self.view.addSubview( mUICollectionView )
        
    }
    //返回分区个数
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 10
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "itemid", for: indexPath)
        
        cell.backgroundColor = UIColor.red
        
        return cell
    
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print( "点击了\(indexPath.row)" )
    }
    //UICollectionViewDelegateFlowLayout 为 UICollectionViewDelegate子类  必须实现UICollectionViewDelegateFlowLayout协议才有下面的函数
    //动态设置item高宽
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        if( indexPath.row%2 == 0 ){
            return CGSize(width: 50, height: 50)
        }else{
            return CGSize(width: 100, height: 100)
        }
    }
    
    //瀑布流见 287页
    
    
}
